package cn.com.qiniu;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.uthink.util.EncodeUtil;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;

public class UthinkUploader {

	// http://odum9helk.qnssl.com/resource/gogopher.jpg?imageView2/1/w/200/h/200
	// //裁剪正中部分，等比缩小
	// http://odum9helk.qnssl.com/resource/gogopher.jpg?imageView2/2/w/200
	// //宽度固定，高度等比缩小

	private static int counter = 0;
	private static Auth auth;
	private static UploadManager uploadManager;
	private static BucketManager bucketManager;
	private static OperationManager operationMgr;

	public static final Map<String, Integer> sourceType = new HashMap<String, Integer>();

	static {// 静态块
		// System.out.println("-----初始化-----");
		auth = Auth.create(QiniuConfig.qiniu_acesskey,
				QiniuConfig.qiniu_secretkey);
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		uploadManager = new UploadManager(cfg);
		bucketManager = new BucketManager(auth, cfg);

		// 执行操作的管理对象
		operationMgr = new OperationManager(auth, new Configuration(
				Zone.zone0()));

		// 初始化
		sourceType.put("png", 0);
		sourceType.put("PNG", 0);
		sourceType.put("jpg", 0);
		sourceType.put("JPG", 0);
		sourceType.put("gif", 0);
		sourceType.put("GIF", 0);
		sourceType.put("mp3", 1);
		sourceType.put("MP3", 1);
		sourceType.put("wav", 1);
		sourceType.put("WAV", 1);
		sourceType.put("wma", 1);
		sourceType.put("WMA", 1);
		sourceType.put("asf", 1);
		sourceType.put("ASF", 1);
		sourceType.put("avi", 2);
		sourceType.put("AVI", 2);
		sourceType.put("mp4", 2);
		sourceType.put("MP4", 2);
		sourceType.put("wmv", 2);
		sourceType.put("WMV", 2);
		sourceType.put("rmvb", 2);
		sourceType.put("RMVB", 2);
	}

	/**
	 * @Title: getUpToken
	 * @Description: 获取上传token
	 * @param avthumbType
	 *            文件类型 0图片，1音频， 2视频
	 * @return String
	 */
	private static String getUpToken() {
		return auth.uploadToken(QiniuConfig.qiniu_bucketname);
	}

	private static String encodingFilename(String filename) {
		return EncodeUtil.encodeMD5(filename + System.nanoTime() + counter++)
				+ "." + filename;
	}

	public boolean delete(String filePath) {
		String sufixString = null;
		int slashIndex = filePath.indexOf(".");
		if (slashIndex >= 0) {
			sufixString = filePath.substring(slashIndex + 1);
		}
		String filename = encodingFilename(sufixString);
		try {
			bucketManager.delete(QiniuConfig.qiniu_bucketname, filename);
			return true;
		} catch (QiniuException e) {
			Response r = e.response;
			System.out.println(r.toString());
		}
		return false;
	}

	/**
	 * @Title: send
	 * @Description:发送文件到qiniu
	 * @param fileName
	 *            文件名
	 * @param data
	 *            文件流
	 * @param sourceType
	 *            文件类型 0图片，1音频， 2视频
	 * @throws Exception
	 * @return String
	 */
	public static String send(String fileName, byte[] data, Integer sourceType)
			throws Exception {
		String sufixString = null;
		int slashIndex = fileName.indexOf(".");
		if (slashIndex >= 0) {
			sufixString = fileName.substring(slashIndex + 1);
		}
		String filename = encodingFilename(sufixString);
		Response res = null;
		try {
			res = uploadManager.put(data, filename, getUpToken());
			// res = uploadManager.put(data, filename, getUpToken(), null, null,
			// false);
			StringMap stringMap = res.jsonToMap();
			// System.err.println("-------" + res.toString());
			// System.err.println("---url----" +
			// stringMap.get("key").toString());

			// 视频转码
			if (sourceType == 2) {
				transcoding(stringMap.get("key").toString(),
						stringMap.get("key").toString());
			}

			return QiniuConfig.qiniu_acessurl + "/"
					+ stringMap.get("key").toString();
		} catch (QiniuException e) {
			e.printStackTrace();
			System.out.println(e.response.toString());
		}
		return null;
	}

	/**
	 * 转码
	 */
	private static void transcoding(String filename, String pipeline_name) {
		String bucket = QiniuConfig.qiniu_bucketname; // 存储空间名称
		String key = filename; // 存储空间中视频的文件名称
		String newKey = filename; // 转码后，另存的文件名称
		String pipeline = pipeline_name; // 处理队列

		String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey); // saveas接口
																				// 参数
		String fops = "avthumb/mp4/vcodec/libx264|saveas/" + saveAs; // 处理命令
																		// avthumb
																		// 和
																		// saveas
																		// 通过管道符
																		// |
																		// 进行连接
		try {
			// 执行转码和另存 操作
			String persistentId = operationMgr.pfop(bucket, key, fops,
					new StringMap().put("persistentPipeline", pipeline));
			System.out.println(persistentId);
		} catch (QiniuException e) {
			String errorCode = String.valueOf(e.response.statusCode);
			System.out.println(errorCode);
			e.printStackTrace();
		}
	}

	/**
	 * @Title: getSourceType
	 * @Description: 获取文件的类型
	 * @param fileName
	 * @return Integer
	 */
	public static Integer getSourceType(String fileName) {
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		Integer result = (Integer) sourceType.get(suffix);
		return result;
	}

	public static void main(String args[]) {
		System.out.println(getSourceType("dawdadwa.pnga"));
	}
}
